#include "event_loop_thread_pool.h"


namespace rr {
namespace nio {

EventLoopThreadPool::EventLoopThreadPool(const std::string& name)
: name_(name)
{

}

EventLoopThreadPool::~EventLoopThreadPool()
{

}

int32_t EventLoopThreadPool::Start(uint32_t num)
{
    for(uint32_t i = 0; i < num; ++i) {
        EventLoopThread::Sptr loop_thread = std::make_shared<EventLoopThread>(name_ + std::to_string(i));
        loop_thread->StartLoop();
        threads_.emplace_back(loop_thread);
    }

    return 0;
}

void EventLoopThreadPool::Stop()
{
    for(auto& thread : threads_) {
        thread->StopLoop();
    }

    return;
}

EventLoopThread::Sptr EventLoopThreadPool::GetThread(uint32_t index)
{
    if(threads_.empty()) {
        return nullptr;
    }

    return threads_[index % threads_.size()];
}

EventLoop::Sptr EventLoopThreadPool::GetLoopByIndex(uint32_t index)
{
    EventLoopThread::Sptr thread = GetThread(index);
    if(thread == nullptr) {
        return nullptr;
    }

    return thread->GetLoop();
}

EventLoop::Sptr EventLoopThreadPool::GetNextLoop()
{
    EventLoop::Sptr loop = nullptr;
    if(!threads_.empty()) {
        uint32_t index = index_ % threads_.size();
        index_++;
        loop = threads_[index]->GetLoop();
	}

	return loop;    
}

} //namespace 
} //namespace 
